using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using DG.Tweening;

namespace UI.Common
{
    /// <summary>
    /// 提示系统 - 支持多个提示同时显示，带有向上飘动和淡出动画
    /// </summary>
    public class ToastSystem : MonoBehaviour
    {
        [Header("提示配置")]
        [SerializeField] private GameObject toastPrefab;
        [SerializeField] private Transform toastContainer;
        [SerializeField] private TMP_FontAsset toastFont; // 提示字体
        [SerializeField] private float toastSpacing = 10f; // 提示间距（减小间距，因为现在是基于实际高度计算）
        [SerializeField] private float displayDuration = 4f; // 显示持续时间
        [SerializeField] private float fadeOutDuration = 0.3f; // 淡出时间
        
        // 单例实例
        private static ToastSystem instance;
        public static ToastSystem Instance
        {
            get
            {
                if (instance == null)
                {
                    // 尝试在场景中查找
                    instance = FindObjectOfType<ToastSystem>();
                    
                    // 如果没找到，创建一个
                    if (instance == null)
                    {
                        GameObject toastSystemObj = new GameObject("ToastSystem");
                        instance = toastSystemObj.AddComponent<ToastSystem>();
                        DontDestroyOnLoad(toastSystemObj);
                        instance.Initialize();
                    }
                }
                return instance;
            }
        }
        
        // 活跃的提示列表
        private List<ToastItem> activeToasts = new List<ToastItem>();
        
        /// <summary>
        /// 提示项数据结构
        /// </summary>
        private class ToastItem
        {
            public GameObject gameObject;
            public RectTransform rectTransform;
            public CanvasGroup canvasGroup;
            public TextMeshProUGUI textComponent;
            public float startY;
            public Sequence animationSequence;
        }
        
        #region 初始化
        
        private void Awake()
        {
            if (instance == null)
            {
                instance = this;
                DontDestroyOnLoad(gameObject);
                Initialize();
            }
            else if (instance != this)
            {
                Destroy(gameObject);
            }
        }
        
        /// <summary>
        /// 初始化提示系统
        /// </summary>
        private void Initialize()
        {
            Debug.Log("[ToastSystem] 初始化提示系统");
            
            // 加载字体
            LoadFont();
            
            // 如果没有预设的容器，创建Canvas和容器
            if (toastContainer == null)
            {
                CreateCanvas();
            }
            
            // 创建提示预制体
            CreateToastPrefab();
            
            Debug.Log("[ToastSystem] 提示系统初始化完成");
        }
        
        /// <summary>
        /// 加载字体
        /// </summary>
        private void LoadFont()
        {
            if (toastFont == null)
            {
                toastFont = Resources.Load<TMP_FontAsset>("Font/W120 SDF");
                if (toastFont == null)
                {
                    Debug.LogWarning("[ToastSystem] 无法加载字体 Font/W120 SDF，将使用默认字体");
                }
                else
                {
                    Debug.Log("[ToastSystem] 成功加载字体: W120 SDF");
                }
            }
        }
        
        /// <summary>
        /// 创建Canvas
        /// </summary>
        private void CreateCanvas()
        {
            // 检查是否已有Canvas
            Canvas canvas = GetComponent<Canvas>();
            if (canvas == null)
            {
                canvas = gameObject.AddComponent<Canvas>();
                canvas.renderMode = RenderMode.ScreenSpaceOverlay;
                canvas.sortingOrder = 1000; // 确保在最上层
                
                // 添加CanvasScaler
                CanvasScaler scaler = gameObject.AddComponent<CanvasScaler>();
                scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
                scaler.referenceResolution = new Vector2(1920, 1080);
                scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
                scaler.matchWidthOrHeight = 0.5f;
                
                // 添加GraphicRaycaster
                gameObject.AddComponent<GraphicRaycaster>();
            }
            
            // 创建容器
            if (toastContainer == null)
            {
                GameObject containerObj = new GameObject("ToastContainer");
                containerObj.transform.SetParent(transform);
                
                RectTransform containerRect = containerObj.AddComponent<RectTransform>();
                containerRect.anchorMin = new Vector2(0.5f, 1f);
                containerRect.anchorMax = new Vector2(0.5f, 1f);
                containerRect.pivot = new Vector2(0.5f, 1f);
                containerRect.anchoredPosition = new Vector2(0, -100f); // 距离顶部100像素
                containerRect.sizeDelta = new Vector2(400f, 0f);
                
                toastContainer = containerRect;
            }
        }
        
        /// <summary>
        /// 创建提示预制体
        /// </summary>
        private void CreateToastPrefab()
        {
            if (toastPrefab != null) return;
            
            // 创建提示预制体
            GameObject prefab = new GameObject("ToastPrefab");
            
            // 添加RectTransform
            RectTransform rectTransform = prefab.AddComponent<RectTransform>();
            rectTransform.sizeDelta = new Vector2(400f, 60f); // 设置默认宽度和高度
            
            // 添加CanvasGroup用于透明度控制
            CanvasGroup canvasGroup = prefab.AddComponent<CanvasGroup>();
            
            // 创建背景
            GameObject background = new GameObject("Background");
            background.transform.SetParent(prefab.transform);
            
            RectTransform bgRect = background.AddComponent<RectTransform>();
            bgRect.anchorMin = Vector2.zero;
            bgRect.anchorMax = Vector2.one;
            bgRect.offsetMin = Vector2.zero;
            bgRect.offsetMax = Vector2.zero;
            
            Image bgImage = background.AddComponent<Image>();
            bgImage.color = new Color(0f, 0f, 0f, 0.8f); // 黑色透明底
            bgImage.raycastTarget = false; // 不接收射线检测
            
            // 创建文本
            GameObject textObj = new GameObject("Text");
            textObj.transform.SetParent(prefab.transform);
            
            RectTransform textRect = textObj.AddComponent<RectTransform>();
            textRect.anchorMin = new Vector2(0f, 0f);
            textRect.anchorMax = new Vector2(1f, 1f);
            textRect.offsetMin = new Vector2(15f, 10f); // 左下内边距
            textRect.offsetMax = new Vector2(-15f, -10f); // 右上内边距
            
            TextMeshProUGUI textComponent = textObj.AddComponent<TextMeshProUGUI>();
            textComponent.text = "提示文本";
            textComponent.color = Color.white; // 白色字体
            textComponent.fontSize = 24f; // 大一些的字体
            textComponent.fontStyle = FontStyles.Bold;
            textComponent.alignment = TextAlignmentOptions.Center;
            textComponent.enableWordWrapping = true;
            
            // 只给文本添加ContentSizeFitter
            ContentSizeFitter textSizeFitter = textObj.AddComponent<ContentSizeFitter>();
            textSizeFitter.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
            textSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
            
            // 设置字体
            if (toastFont != null)
            {
                textComponent.font = toastFont;
                Debug.Log("[ToastSystem] 已设置字体: W120 SDF");
            }
            
            toastPrefab = prefab;
            toastPrefab.SetActive(false);
        }
        
        #endregion
        
        #region 公共接口
        
        /// <summary>
        /// 显示提示
        /// </summary>
        /// <param name="message">提示内容</param>
        /// <param name="duration">显示时长（秒）</param>
        public static void ShowToast(string message, float duration = 4f)
        {
            Instance.ShowToastInternal(message, duration);
        }
        
        /// <summary>
        /// 显示提示（带颜色）
        /// </summary>
        /// <param name="message">提示内容</param>
        /// <param name="textColor">文字颜色</param>
        /// <param name="duration">显示时长（秒）</param>
        public static void ShowToast(string message, Color textColor, float duration = 4f)
        {
            Instance.ShowToastInternal(message, duration, textColor);
        }
        
        /// <summary>
        /// 显示提示（带背景和文字颜色）
        /// </summary>
        /// <param name="message">提示内容</param>
        /// <param name="textColor">文字颜色</param>
        /// <param name="backgroundColor">背景颜色</param>
        /// <param name="duration">显示时长（秒）</param>
        public static void ShowToast(string message, Color textColor, Color backgroundColor, float duration = 4f)
        {
            Instance.ShowToastInternal(message, duration, textColor, backgroundColor);
        }
        
        #endregion
        
        #region 内部实现
        
        /// <summary>
        /// 内部显示提示实现
        /// </summary>
        private void ShowToastInternal(string message, float duration = 4f, Color? textColor = null, Color? backgroundColor = null)
        {
            if (string.IsNullOrEmpty(message)) return;
            
            Debug.Log($"[ToastSystem] 显示提示: {message}");
            
            // 创建提示实例
            ToastItem toastItem = CreateToastItem(message, textColor, backgroundColor);
            
            // 添加到活跃列表
            activeToasts.Add(toastItem);
            
            // 设置Toast位置在中间
            toastItem.rectTransform.anchoredPosition = Vector2.zero;
            toastItem.startY = 0f;
            
            // 开始动画
            StartToastAnimation(toastItem, duration);
        }
        
        /// <summary>
        /// 创建提示项
        /// </summary>
        private ToastItem CreateToastItem(string message, Color? textColor = null, Color? backgroundColor = null)
        {
            // 实例化预制体
            GameObject toastObj = Instantiate(toastPrefab, toastContainer);
            toastObj.SetActive(true);
            
            ToastItem item = new ToastItem
            {
                gameObject = toastObj,
                rectTransform = toastObj.GetComponent<RectTransform>(),
                canvasGroup = toastObj.GetComponent<CanvasGroup>()
            };
            
            // 获取文本组件
            item.textComponent = toastObj.GetComponentInChildren<TextMeshProUGUI>();
            if (item.textComponent != null)
            {
                item.textComponent.text = message;
                
                // 设置字体
                if (toastFont != null)
                {
                    item.textComponent.font = toastFont;
                }
                
                // 设置文字颜色
                if (textColor.HasValue)
                {
                    item.textComponent.color = textColor.Value;
                }
            }
            
            // 设置背景颜色
            if (backgroundColor.HasValue)
            {
                Image bgImage = toastObj.GetComponentInChildren<Image>();
                if (bgImage != null)
                {
                    bgImage.color = backgroundColor.Value;
                }
            }
            
            // 初始化透明度
            item.canvasGroup.alpha = 0f;
            
            // 更新Toast高度
            StartCoroutine(UpdateToastHeightNextFrame(item));
            
            return item;
        }
        
        /// <summary>
        /// 在下一帧更新Toast高度
        /// </summary>
        private IEnumerator UpdateToastHeightNextFrame(ToastItem item)
        {
            yield return null; // 等待一帧让文本组件计算完成
            
            UpdateToastHeight(item);
        }
        
        /// <summary>
        /// 更新Toast高度以适应文本内容
        /// </summary>
        private void UpdateToastHeight(ToastItem item)
        {
            if (item.textComponent == null) return;
            
            // 强制刷新文本布局
            LayoutRebuilder.ForceRebuildLayoutImmediate(item.textComponent.rectTransform);
            
            // 获取文本的实际高度
            float textHeight = item.textComponent.preferredHeight;
            
            // 计算总高度（文本高度 + 上下内边距）
            float totalHeight = textHeight + 20f; // 上下各10像素内边距
            
            // 设置最小高度
            if (totalHeight < 40f)
            {
                totalHeight = 40f;
            }
            
            // 更新Toast的高度
            Vector2 currentSize = item.rectTransform.sizeDelta;
            item.rectTransform.sizeDelta = new Vector2(currentSize.x, totalHeight);
            
            Debug.Log($"[ToastSystem] 更新Toast高度: 文本高度={textHeight:F1}, 总高度={totalHeight:F1}");
        }
        

        
        /// <summary>
        /// 开始提示动画
        /// </summary>
        private void StartToastAnimation(ToastItem item, float duration)
        {
            // 创建动画序列
            item.animationSequence = DOTween.Sequence();
            
            // 淡入动画（立即显示）
            item.animationSequence.Append(item.canvasGroup.DOFade(1f, 0.1f));
            
            // 等待显示时间
            item.animationSequence.AppendInterval(duration);
            
            // 淡出动画
            item.animationSequence.Append(item.canvasGroup.DOFade(0f, fadeOutDuration).SetEase(Ease.InCubic));
            
            // 动画完成后移除
            item.animationSequence.OnComplete(() => RemoveToastItem(item));
        }
        
        /// <summary>
        /// 移除提示项
        /// </summary>
        private void RemoveToastItem(ToastItem item)
        {
            if (item == null || item.gameObject == null) return;
            
            // 从活跃列表中移除
            activeToasts.Remove(item);
            
            // 销毁游戏对象
            if (item.gameObject != null)
            {
                Destroy(item.gameObject);
            }
            
            Debug.Log($"[ToastSystem] 提示已移除，当前活跃提示数量: {activeToasts.Count}");
        }
        
        #endregion
        
        #region 清理
        
        /// <summary>
        /// 清除所有提示
        /// </summary>
        public static void ClearAllToasts()
        {
            if (instance != null)
            {
                instance.ClearAllToastsInternal();
            }
        }
        
        /// <summary>
        /// 内部清除所有提示实现
        /// </summary>
        private void ClearAllToastsInternal()
        {
            foreach (var item in activeToasts)
            {
                if (item.animationSequence != null)
                {
                    item.animationSequence.Kill();
                }
                
                if (item.gameObject != null)
                {
                    Destroy(item.gameObject);
                }
            }
            
            activeToasts.Clear();
            Debug.Log("[ToastSystem] 已清除所有提示");
        }
        
        private void OnDestroy()
        {
            ClearAllToastsInternal();
            
            if (instance == this)
            {
                instance = null;
            }
        }
        
        #endregion
    }
} 